/**
 * This file is part of the dspace-poltman project http://www.poltman.com.
 *
 * This is free software; you can redistribute it and/or modify it under
 * the terms of DuraSpace DSpace license detailed in the LICENSE and NOTICE 
 * files at the root of the source tree and available online at
 * http://www.dspace.org/license/
 * 
 */

package com.poltman.dscentral.communities;

import org.apache.log4j.Logger;
import org.zkforge.ckez.CKeditor;
import org.zkoss.zk.ui.select.SelectorComposer;
import org.zkoss.zk.ui.select.annotation.Listen;
import org.zkoss.zk.ui.select.annotation.Wire;
import org.zkoss.zkplus.spring.SpringUtil;
import org.zkoss.zul.Intbox;
import org.zkoss.zul.Messagebox;


import com.poltman.dscentral.db.service.dspace.CommunityService;
import com.poltman.dscentral.core.CoreSessionData;
import com.poltman.dscentral.core.dspace.Communities;

/**
 * 
 * @author z.ciok@poltman.com
 *
 */
public class SaveCommunityIntroductoryText extends SelectorComposer<CKeditor>  {

	private static final long serialVersionUID = 8779071010650142687L;
	private static Logger log = Logger.getLogger(SaveCommunityIntroductoryText.class);
	
	@Wire
	Intbox communityIdIntbox;
	
	@Wire
	CKeditor edIntroductoryText;
	
	/**
	 * 
	 */
	@Listen("onSave = ckeditor#edIntroductoryText")
	public void saveIntroductoryText() {
		try {
			if (communityIdIntbox.getValue() == null) {
				//TODO: i18n
				Messagebox.show("Select community.", "DSCentral Error", 0,  Messagebox.ERROR);
				return;
			} else {
				CommunityService  communityService = (CommunityService) SpringUtil.getBean("communityService");
				if ((edIntroductoryText.getValue() == null) || (edIntroductoryText.getValue().isEmpty())) {
					//TODO: i18n, to remove ?
					Messagebox.show("Introductory Text can not be null.", "DSCentral Error", 0,  Messagebox.ERROR);	
					return;
				} else {
					communityService.setFixedIntroductoryTextFor(edIntroductoryText.getValue(), communityIdIntbox.getValue());					
				}	
			}	
		} catch (Exception e) {
			log.error("Error: saveIntroductoryText; ", e);
			//TODO: i18n
			Messagebox.show("Introductory Text save error...", "DSCentral Error", 0,  Messagebox.ERROR);
			return;
		}
		
		CoreSessionData coreSessionData = (CoreSessionData) SpringUtil.getBean("coreSessionData");
		Communities communities = (Communities) coreSessionData.getAttribute("Communities");
		try {
			CommunityUtils.refreshCommunityTree(communities);
		} catch (Exception e) {
			log.error("saveIntroductoryText ", e);
		}
		
		//TODO: i18n
		Messagebox.show("Introductory Text has been saved...", "DSCentral", 0,  Messagebox.INFORMATION);
	}	
}
